#!/bin/sh
NAME=$1
URL=$2
TAG=$3
JAYDIR=".local/share/JayMark"
BROWSER="qupzilla"
BROWSER_ARGS=""


cd ~/
mkdir -p ${JAYDIR}
touch ${JAYDIR}/names.bm
touch ${JAYDIR}/urls.bm

if [ -z "$NAME" ]; then
BOOKMARK=$(cat ${JAYDIR}/urls.bm | grep "$(cat ${JAYDIR}/names.bm | dmenu -i -p 'Bookmarks' | sed 's/(.*)//g')" | sed 's/.*\!//g')
${BROWSER} ${BROWSER_ARGS} ${BOOKMARK} >> /dev/null &
exit 1
fi

if [ "$NAME" = help ]; then
	echo "jaymark '[NAME]' '[URL]' '[TAG]'"
	echo "jaymark 'My NotABug' 'https://notabug.org/jayvii' 'nab,mynab'"
	echo ""
	exit 1
fi

if [ -z "$NAME" ] && [ -z "$URL" ]; then
	echo "You need at least a unique name and an url!"
	exit 1
fi

NAME_EXISTS=$(cat ${JAYDIR}/names.bm | grep "${NAME}")
if [ -z "$NAME_EXISTS" ]; then
	echo "${NAME} (${TAG})" >> ${JAYDIR}/names.bm
	echo "${NAME} !${URL}" >> ${JAYDIR}/urls.bm
	exit 4
else
	echo "This name already exists in your database."
	echo "Please choose another one."
	exit 5
fi
